import DrawerFooter from '@/components/DrawerFooter';
import { Button, Form, Input, Select, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import { useStore, useService } from '@/hooks';
import React, { useState, useRef, useEffect } from 'react';
import DataAutoComplete from '@/components/DataAutoComplete';
import { searchStation } from '../stores/api';
import MapModal from '@/components/MapModal';
import { observable, toJS } from 'mobx';
import { observer } from 'mobx-react-lite';
import { deconstructionMapObj, arrTransferObj } from '@/utils/util';

const FormItem = Form.Item;

function ChargeForm({ data, stationInfo, onSubmit, onCancel }) {
  const { scStationStore: store } = useStore();
  const [map, setMap] = useState({ show: false, coord: '', cityName: '' });
  const [state] = useState(() => observable({}));
  const { apiLbs } = useService();
  const formField = useRef(); // 用于保存通过saveField获取到的field实例

  useEffect(() => {
    _.assign(state, { ...data });
  }, [data]);

  const handleSetData = (__, items) => {
    const { name, value } = items;
    _.set(state, name, value);
  };

  const handleMapOpen = async () => {
    const { cityText } = toJS(stationInfo);
    const { longLat = '' } = toJS(state);
    let coord = longLat;
    let currentCity = cityText;
    if (!longLat) {
      const r = await apiLbs.placeSearch({ region: currentCity, keyword: state?.address });
      const { location, city, province } = r[0];
      currentCity = city || province;
      const { lat, lng } = arrTransferObj(location);
      coord = deconstructionMapObj({ lat, lng });
    }
    setMap({ show: true, coord, cityName: currentCity });
  };

  const handleCoordPicked = async (coord) => {
    const location = deconstructionMapObj(toJS(coord));
    _.set(state, 'longLat', location);
    formField.current.reset(['longLat']);
    setMap({ show: false });
  };

  const handleOnSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      return;
    }
    onSubmit?.(state);
  };

  return (
    <Form
      labelAlign="top"
      fullWidth
      value={toJS(state)}
      onChange={handleSetData}
      onSubmit={handleOnSubmit}
      saveField={(f) => { formField.current = f; }}
    >
      <FormItem
        label={t`公司名称`}
        name="companyId"
        required
        useLabelForErrorMessage
      >
        <Select>
          {store.operatingCompanys.map((item) => <Select.Option value={item.value}>{item.label}</Select.Option>)}
        </Select>
      </FormItem>
      <FormItem
        label={t`站点(运营公司匹配站点, 三地通可为空)`}
        name="stationId"
        required
        useLabelForErrorMessage
      >
        <DataAutoComplete
          hasClear
          placeholder={t`请输入需要匹配的站点名称`}
          labelField="name"
          valueField="stationId"
          onFocus={() => {
            if (!state?.companyId) {
              Message.warning(t`请先设置运营公司`);
            }
          }}
          args={{ stationId: state?.stationId, ...(state?.companyId !== 'platform' && { companyId: state?.companyId }) }}
          onFetch={(_, args) => {
            const { keyword } = args || {};
            return keyword ? searchStation({ keyword, ...(state?.companyId !== 'platform' && { companyId: state?.companyId }) }) : searchStation(args);
          }}
        />
      </FormItem>
      <FormItem
        label={t`经纬度`}
        name="longLat"
        required
        useLabelForErrorMessage
      >
        <Input
          placeholder={t`选择经纬度`}
          addonAfter={<Button type="primary" onClick={() => handleMapOpen()}>{t`获取经纬度`}</Button>}
        />
      </FormItem>
      <FormItem
        label={t`链接`}
        name="link"
        required
        useLabelForErrorMessage
      >
        <Input placeholder={t`请输入链接`} />
      </FormItem>
      <FormItem
        label={t`班次提示内容`}
        name="prompt"
      >
        <Input placeholder={t`请输入班次提示内容`} />
      </FormItem>
      <FormItem
        label={t`详细地址`}
        name="address"
        required
        useLabelForErrorMessage
      >
        <Input.TextArea placeholder={t`请输入详细地址`} />
      </FormItem>
      <DrawerFooter>
        <FormItem>
          <Form.Submit validate type="primary" onClick={onSubmit}>{t`保存`}</Form.Submit>
          <Button style={{ marginLeft: 8 }} onClick={onCancel}>{t`取消`}</Button>
        </FormItem>
      </DrawerFooter>
      <MapModal
        visible={map.show}
        coord={map.coord}
        cityName={map.cityName}
        containerId={'scStationChargeForm'}
        onClose={() => setMap({ show: false })}
        onCancel={() => setMap({ show: false })}
        onPick={handleCoordPicked}
      />
    </Form>
  );
}

export default observer(ChargeForm);
